package nl.vu.few.ibivu.biomodels.client.activity;

import java.util.List;

import nl.vu.few.ibivu.biomodels.client.ModelDataSource;
import nl.vu.few.ibivu.biomodels.client.ModelPager;
import nl.vu.few.ibivu.biomodels.client.event.MessageBroadcastType;
import nl.vu.few.ibivu.biomodels.client.ui.view.ModelBrowsingView;
import nl.vu.few.ibivu.biomodels.shared.Model;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.smartgwt.client.data.events.ErrorEvent;
import com.smartgwt.client.data.events.HandleErrorHandler;

public class ModelBrowsingActivity extends PresenterActivity implements ModelBrowsingView.Presenter, HandleErrorHandler {
	
	ModelBrowsingView view;
	ModelPager pager;
	ModelDataSource dataSource;
	HandlerRegistration registration;
	
	
	@Inject
	public ModelBrowsingActivity(EventBus eventBus, PlaceController placeController, ModelDataSource dataSource, ModelPager pager, ModelBrowsingView view) {
		super(eventBus, placeController);
		setLoginRequired(true);
		this.pager = pager;
		this.dataSource = dataSource;
		this.view = view;
		registration = this.dataSource.addHandleErrorHandler(this);
	}
	
	@Override
	public Widget getView() {
		return view.asWidget();
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		view.setPresenter(this);
		panel.setWidget(view);
	}
	
	@Override
	public void onCancel() {
		// Avoid that the current presenter receives messages while waiting to be disposed
		if (registration != null) registration.removeHandler();
		super.onCancel();
	}

	@Override
	public void onStop() {
		// Avoid that the current presenter receives messages while waiting to be disposed
		if (registration != null) registration.removeHandler();
		super.onStop();
	}

	@Override
	public ModelDataSource getDataSource() {
		return dataSource;
	}

	@Override
	public void getNextPage() {
		pager.getNextPage();
	}

	@Override
	public String getCursor() {
		return pager.getCursor();
	}

	@Override
	public void setCursor(String cursor) {
		pager.setCursor(cursor);
	}

	@Override
	public void pageReceived(List<Model> results, int totalRows) {
		// TODO
	}

	@Override
	public void onHandleError(ErrorEvent event) {
		event.cancel();
		broadcastMessage(MessageBroadcastType.ERROR, event.getResponse().getAttribute("errorMessage"));
	}
}
